/**
 * created by guyi 2018.01.18
 */

var express = require('express');
var router = express.Router();
var User = require('../models/User');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var redis = require("redis");
var yzmService = require("../routes/yzmService");
var client = redis.createClient(6379, "127.0.0.1");
const UA_List = require('./UA_List');
/**
 * 用户微信授权登录后获取token
 * 
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function wechatLogin(req, res, next) {
    if (!req.query.code || !req.query.nickName || !req.query.avatarUrl) {
        res.send({
            code: 401,
            message: 'code or nickName or avatarUrl is required'
        })
    } else {
        const code = req.query.code
        console.log(code)
        getUserInfoFromWechat(code).then(function (result) {
            result = JSON.parse(result)
            result.nickName = req.query.nickName //用户昵称
            result.avatarUrl = req.query.avatarUrl //用户头像

            if (result.errcode) {
                res.send({
                    code: result.errcode,
                    message: result.errmsg
                }) //code 非法
            } else {
                var check = new Promise((resolve, reject) => {
                    User.findOne({
                        "openid": result.openid
                    }, (err, resp) => {
                        if (err) {
                            console.log('ERROR:' + err);
                        } else {
                            resolve(resp);
                        }
                    });
                })
                check.then(function (value) {
                    if (!value) {
                        var UserEntity = new User(result);
                        UserEntity.save(function (err, resp) {
                            if (err) {
                                console.log('ERROR:' + err);
                            }
                        })
                        var token = jwt.sign(result, 'thefirstminappofvtmer');
                        res.send({
                            code: 405,
                            message: 'not bind the account',
                            data: token
                        })
                    } else {
                        var token = jwt.sign(value, 'thefirstminappofvtmer');
                        res.send({
                            code: 200,
                            message: 'ok',
                            data: token,
                            openid: result.openid
                        })
                    }
                })
            }
        })
    }
}

// 请求微信接口获取用户信息
function getUserInfoFromWechat(code) {
    return new Promise((resolve, reject) => {
        var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx45380ff8bc1c2e10&secret=87c693361e5cdfe9f5be081ac3bcd425&js_code=' + code + '&grant_type=authorization_code'
        superagent.get(url)
            .end(function (err, res) {
                if (err) {
                    reject(err);
                };
                resolve(res.text);
            })
    })
}
/**
 * 绑定学号
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function bind(req, res, next) {
    var {
        token,
        account,
        password,
        yzm,
        cookie
    } = req.body

    if ( token && username && password && yzm && cookie) {
        //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
        try {
            let decoded = jwt.verify(token, 'thefirstminappofvtmer');
            var openid = decoded.openid;
        } catch (err) {
            res.send({code:500, message:'token invalid'});
        }
        var result = toCheckIfAccess(username, password, yzm, cookie);
        result.then(function (value) {
            if (value == 0) { // 登录成功
                yzmService.setCookieIntoRedis(username,cookie)
                var userInfo = new Promise((resolve, reject) => {
                    User.findOne({openid:oepnid}, (err, resp) => {
                        if (err) {
                            console.log(err);
                        } else {
                            resolve(resp);
                        }
                    })
                });
                userInfo.then(function (value) {
                    if (!value) { // 找到该微信用户
                        let update_value = {
                            account:account,
                            password:password
                        }
                        // 更新数据
                        User.update({openid:openid}, update_value, function (err, resp) {
                            if (err) {
                                console.log(err);
                            } else {
                                res.send({code:200, message:'Bind successfully!'})
                            }
                        }) 
                    } else {
                        console.log('WARNING:Invalid Request');
                        res.send({code:500, message:'wechat not found'});
                    }
                });
            } else {
                res.send({code:500, message:'code， username, password error'});
            }
        });
    } else {
        res.send({code:500, message:'params required'});
    }
}

    
async function login(req, res, next) {
    var { username, password, yzm, cookie } = req.body
    console.log(req.body)
    if ( username && password && yzm && cookie) {
        var loginResult = await toCheckIfAccess(username, password, yzm, cookie);
        if (loginResult == 0) {
            var isExistUser =  await User.findOne({account:username})
            console.log(isExistUser)
            if (!isExistUser) {
                User.create({account:username, password:password})
                await yzmService.setCookieIntoRedis(username, cookie)
                var token = jwt.sign(req.body, 'thefirstminappofvtmer');
                res.send({code:200, message:'ok', data:{cookie:cookie,token:token}})
            } else {
                User.findByIdAndUpdate(isExistUser._id, {password:password})
                await yzmService.setCookieIntoRedis(username, cookie)                
                var token = jwt.sign(req.body, 'thefirstminappofvtmer');
                res.send({code:200, message:'ok', data:{cookie:cookie,token:token}})
            }
        } else {
								console.log('here');
            res.send({code:500, message:'login fail'})
        }
    } else {
        res.send({code:500, message:'require params'})
    }
}
  
function toCheckIfAccess(username, password, yzm, cookie) {
    return new Promise((resolve, reject) => {
        const baseUrl = 'http://jxfw.gdut.edu.cn/new/login'
        let formData = {
            account: username, //'3114006472'
            pwd: password, //'472040743lzh'
            verifycode: yzm,
        }
        superagent
            .post(baseUrl)
            .set('User-agent', UA_List.get())
            .set("Cookie", cookie)
            .type("form")
            .send(formData)
            .end(function (err, res) {
                if (err) {
                    reject(err);
                };
                let result = JSON.parse(res.text)
                if (result.code == 0) {
                    console.log('result' + result.code)
                    resolve(result.code)
                } else {
                    console.log(result);
                    console.log('fail to login:' + username)
                    resolve(1)
                }
        }) //post end函数
    }) //return
}

module.exports = {wechatLogin, login }
